package com.qs.javame.thread.tool;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 测试：Exchanger（交换者）
 */
public class ExchangerTest {

    private static final Exchanger<String> exchanger = new Exchanger<>();

    private static ExecutorService executorService = Executors.newFixedThreadPool(2);

    public static void main(String[] args) {

        executorService.execute(() -> {
            String A = "银行流水A";

            try {
                //一个线程中调用exchange(V)方法，然后阻塞等待另一个线程调用exchange(V)方法
                exchanger.exchange(A);
                System.out.println("等待结束，线程继续执行~");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        executorService.execute(() -> {
            String B = "银行流水B";

            try {
                //另一个线程执行exchange(V)方法，返回值为上一个线程执行exchange(V)中交换的数据，阻塞的线程返回，继续执行。
                String A = exchanger.exchange(B);
                System.out.println("A和B数据是否一致：" + A.equals(B));
                System.out.println("A录入的是：" + A + "，B录入的是：" + B);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        executorService.shutdown();
    }
}
